﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using log4net;
using MRO.ClientApplication.ModelsDto.UtilDto;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace MRO.ClientApplication.Util
{
    public static class Common
    {


        private static ILog logger = LogManager.GetLogger(typeof(Common));
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">数据</param>
        /// <param name="wk"></param>
        /// <param name="sheetname">sheet</param>
        /// <param name="mobanname">哪个模版</param>
        /// <param name="keyField">哪个key字段</param>
        /// <returns></returns>
        public static void Makexls<T>(IList<T> list, HSSFWorkbook wk, string sheetname, string mobanname, string keyField) where T : Execlreport
        {
            var cellStyle = Excelsetbk(wk);

            string sql = "select * from k3xlsinfo where doctype='" + mobanname + "'";
            var k3list = Connection.MRO.GetList<k3xlsinfo>(sql);

            var sheet = wk.GetSheet(sheetname);

            var headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            var glist = list.GroupBy(p => p.billcode);
            int rownum = 0;
            foreach (var gitem in glist)
            {

                int row = 0;
                foreach (var item in gitem)
                {
                    row++;
                    rownum++;
                    var nrow = sheet.CreateRow(rownum);
                    for (int i = 0; i < cellCount; i++)
                    {
                        var cell = nrow.CreateCell(i);
                        cell.CellStyle = cellStyle;

                        string keyvalue = item.GetValue(keyField);

                        var title = sheet.GetRow(0).GetCell(i).ToString();

                        var k3Item = k3list.FirstOrDefault(k => k.title == title && k.key == keyvalue) ?? k3list.FirstOrDefault(k => k.title == title && string.IsNullOrEmpty(k.key));

                        if (k3Item == null) continue;
                        switch (k3Item.mode)
                        {
                            case "g":
                                cell.SetCellValue(k3Item.value);
                                break;
                            case "c":
                                cell.SetCellValue(GetvalueFormat(item, k3Item));
                                break;
                            case "i":
                                cell.SetCellValue(row.ToString());
                                break;
                        }
                    }
                }
            }
        }


        public static string Encode(string realName, DateTime dt)
        {
            var authHost = ConfigurationManager.AppSettings["SSOServerDomain"];
            var accessTokenUrl = authHost + "/api/values/GetAccessToken?userName=" + realName;
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            string result = client.DownloadString(accessTokenUrl);
            var res = JsonConvert.DeserializeObject<CheckAccessToken>(result);

            if (!res.success)
            {
                logger.ErrorFormat("获取AccessToken失败：{0}, user:{1}", result, realName);
            }
            else
            {
                logger.InfoFormat("AccessToken: {0}", result);
            }
            return res.accessToken;
        }


        private static string GetvalueFormat<T>(T item, k3xlsinfo k3Item) where T : Execlreport
        {
            var ivalue = item.GetValue(k3Item.ziduan);
            if (!string.IsNullOrEmpty(k3Item.classtype))
            {
                switch (k3Item.classtype)
                {
                    case "date":
                        ivalue = Convert.ToDateTime(ivalue).ToString(k3Item.FormatType);
                        break;
                    case "money":
                        ivalue = Convert.ToDecimal(ivalue).ToString(k3Item.FormatType);
                        break;
                }
            }
            return ivalue;
        }

        private static ICellStyle Excelsetbk(HSSFWorkbook workbook)
        {
            ICellStyle cellStyle = workbook.CreateCellStyle();
            IFont cellfont = workbook.CreateFont();
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.BorderLeft = BorderStyle.Thin;
            cellStyle.BorderRight = BorderStyle.Thin;
            cellStyle.BorderTop = BorderStyle.Thin;
            cellStyle.SetFont(cellfont);
            return cellStyle;
        }

        public static void GetAction(string fromController, string fromAction, ref string toController, ref string toAction, ref string toView, UserInfo user)
        {
            fromController = fromController.ToLower();
            fromAction = fromAction.ToLower();
            string sql = string.Format(@"select toController,toAction,toView from ActionSelect 
            where fromController='{0}' and fromAction='{1}' and (context='{2}' or context='{3}')", fromController, fromAction, user.cCusCode, user.Custclass);
            var tb = Connection.MRO.ExecuteQuery(sql);
            if (tb == null || tb.Rows.Count == 0) return;
            toController = tb.Rows[0]["toController"].ToString();
            toAction = tb.Rows[0]["toAction"].ToString();
            toView = tb.Rows[0]["toView"].ToString();
        }

        public static string PostUrl(string url, string body, Dictionary<string, string> keyValuePair = null)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "application/json";
            request.ContentType = "application/json";
            request.Timeout = 60 * 1000;
            request.ServicePoint.Expect100Continue = false;

            if (keyValuePair != null)
            {
                foreach (var pair in keyValuePair)
                {
                    request.Headers.Add(pair.Key, pair.Value);
                }
            }

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }

        /// <summary>
        /// client发送
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="keyValuePair"></param>
        /// <returns></returns>
        public static string SendFormData(string url, string body, Dictionary<string, string> keyValuePair = null)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 6 * 1000;

            if (keyValuePair != null)
            {
                foreach (var pair in keyValuePair)
                {
                    request.Headers.Add(pair.Key, pair.Value);
                }
            }

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }

        /// <summary>
        /// 原生写法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="keyValuePair"></param>
        /// <returns></returns>
        public static string SendFormData(string url, Dictionary<string, string> body = null, Dictionary<string, string> keyValuePair = null)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            foreach (var pair in keyValuePair)
            {
                client.DefaultRequestHeaders.Add(pair.Key, pair.Value);
            }
            var content = new FormUrlEncodedContent(body); // 将字典类型转换成 HttpContent 类型
            var httpmessage = client.PostAsync(url, content).Result; // 发送 POST 请求，并获取响应结果
            if (httpmessage.IsSuccessStatusCode)
            {
                var response = httpmessage.Content.ReadAsStringAsync().Result;
                return response;
            }

            return "";

        }

        public static string PostClientUrl<T>(T body, string url, Dictionary<string, string> keyValuePair = null)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            foreach (var pair in keyValuePair)
            {
                client.DefaultRequestHeaders.Add(pair.Key, pair.Value);
            }
            var httpmessage = client.PostAsJsonAsync(url, body).Result;

            if (httpmessage.IsSuccessStatusCode)
            {
                var response = httpmessage.Content.ReadAsStringAsync().Result;
                return response;
            }
            return "";
        }

        public static string TranJson<T>(T t)
        {
            var setting = new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };
            string jsonorder = JsonConvert.SerializeObject(t, Formatting.None, setting);
            return jsonorder;
        }

        public static bool IsUrl(string url)
        {
            return Regex.IsMatch(url, @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?$", RegexOptions.IgnoreCase);
        }


    }
}
